import {Stats, statSync, readdirSync} from "fs"
import {getLogger} from "log4js"
import * as path from "path"

export class Scanner {
  static logger = getLogger("Scanner")

  static scan(dir: string, pattern: string | RegExp, opts: {deep?: boolean, handler?: (string) => void, stopWhenFind?: boolean}) {
    const {deep, handler, stopWhenFind} = opts
    let stat = statSync(dir)

    if (!stat.isDirectory()) {
      Scanner.logger.error("参数错误")
      process.exit(1)
    }

    const files = readdirSync(dir).map(item => path.resolve(dir, item))

    return files.some(file => {
      if (statSync(file).isDirectory()) {
        deep && Scanner.scan(file, pattern, opts)
      } else {
        const isMatch = new RegExp(pattern).test(file)
        isMatch && handler && handler.call(this, file)
        if (isMatch && stopWhenFind) return true
      }
    })
  }

}

